package com.farm.model.view.controller;

import com.farm.model.comm.RSACoder;
import com.farm.model.ddic.entity.Ddic;
import com.farm.model.ddic.service.DdicService;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Calendar;
import java.util.List;
import java.util.Map;

/**
 * 首页接口
 */
@RestController
@RequestMapping("common")
public class CommonController {

    @Autowired
    private DdicService ddicService;

    /**
     * 按照字典分类获取字典列表
     *
     * @return
     */
    @PostMapping("/ddic/{ddicCategory}")
    public List<Ddic> getCategoryList(@PathVariable String ddicCategory) throws Exception {
        return ddicService.getCategoryList(ddicCategory);
    }

    /**
     * 获取公钥加密的时间戳
     *
     * @return
     */
    @PostMapping("/publicKey")
    public String getPublicKey() throws Exception {
        //生成密钥对
        Map<String, Object> keyMap = RSACoder.initKey();
        //公钥
        byte[] publicKey = RSACoder.getPublicKey(keyMap);

        // 设置10分钟有效期
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE, 10);
        long timeInMillis =instance.getTimeInMillis();

        byte[] code2 = RSACoder.encryptByPublicKey(String.valueOf(timeInMillis).getBytes(), publicKey);
        return Base64.encodeBase64String(code2);
    }
}
